package com.itany.ums.servlet;

import com.itany.ums.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月12日9:12
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("====================");
        request.setCharacterEncoding("utf-8");
        String path=request.getServletPath();
        if("/register.user".equals(path)){
            register(request,response);
        }
        if("/login.user".equals(path)){
            login(request,response);
        }
        if("/logout.user".equals(path)){
            logout(request,response);
        }
    }
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求中的数据
        String username= request.getParameter("username");
        String password= request.getParameter("password");
        String phone= request.getParameter("phone");
        String address= request.getParameter("address");

        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String url="jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from ")
                    .append(" t_user ")
                    .append(" where username=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            rs=ps.executeQuery();
            if(rs.next()){
                request.setAttribute("registerMsg","该用户名已经被注册了");
                request.getRequestDispatcher("/register.jsp").forward(request,response);
                return;
            }
            //如果没有注册，实现注册功能
            sql=new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.setString(3,phone);
            ps.setString(4,address);
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求中的数据
        String username= request.getParameter("username");
        String password= request.getParameter("password");
        ResultSet rs=null;
        Connection conn=null;
        PreparedStatement ps=null;
        User user=null;

        String url="jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from ")
                    .append(" t_user ")
                    .append(" where username=? and password=? ")
                    .toString();

            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs=ps.executeQuery();
            if(rs.next()){
                user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                //登录成功，将用户信息存在session中
                request.getSession().setAttribute("user",user);
                response.sendRedirect(request.getContextPath()+"/main.jsp");
                return;
            }
            request.setAttribute("loginMsg","用户名或者密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("loginMsg","服务器内部异常");
        }
        request.getRequestDispatcher("/login.jsp").forward(request,response);

    }
    public void  logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/main.jsp");
    }
}
